package xyz.example.securegeyser;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Base64;

public final class AESCipher {
    private static final String ALG = "AES/GCM/NoPadding";

    public static SecretKey readKey(String b64) {
        byte[] keyBytes = Base64.getDecoder().decode(b64);
        if (keyBytes.length != 32) {
            throw new IllegalArgumentException("AES-256密钥必须为32字节（256位），当前为" + keyBytes.length + "字节");
        }
        return new SecretKeySpec(keyBytes, "AES");
    }

    public static byte[] encrypt(SecretKey key, byte[] plain) throws Exception {
        byte[] iv = SecureRandom.getInstanceStrong().generateSeed(12);
        Cipher cipher = Cipher.getInstance(ALG);
        cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
        byte[] enc = cipher.doFinal(plain);
        ByteBuffer bb = ByteBuffer.allocate(iv.length + enc.length);
        bb.put(iv).put(enc);
        return bb.array();
    }

    public static byte[] decrypt(SecretKey key, byte[] cipherBytes) throws Exception {
        ByteBuffer bb = ByteBuffer.wrap(cipherBytes);
        byte[] iv = new byte[12];
        bb.get(iv);
        byte[] enc = new byte[bb.remaining()];
        bb.get(enc);
        Cipher cipher = Cipher.getInstance(ALG);
        cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
        return cipher.doFinal(enc);
    }
}
